package routers

import (
	"net/http"

	. "gddgame.cc/galaxy/common/dsl/web"
	user "gddgame.cc/galaxy/core/controllers/user"
	"gddgame.cc/galaxy/core/models"
	"gddgame.cc/galaxy/core/sdk"
	"gddgame.cc/galaxy/server/composer"
	"gddgame.cc/galaxy/server/web"
	"gddgame.cc/galaxy/utils/def"
)

func saveJump(context def.Context, app *models.App, channel string, jump string, callback string) (*models.App, string, string, error) {
	if err := context.Set("jump", &jump); err != nil {
		return nil, "", "", err
	}
	return app, channel, callback, nil
}

func jump(context def.Context, result interface{}) error {
	var j string
	if err := context.Get("jump", &j); err != nil {
		j = "/"
	}
	web.Redirect(context, j, http.StatusMovedPermanently)
	return nil
}

func GatewayHandler(path string, builder composer.Builder, router web.Router, client *sdk.AppClient, url string) {
	r := NewSwaggerRouter(path, builder, router, &SwaggerRouterConfig{
		Info: SwaggerInfo{
			Title: "",
		},
	})
	web.Restful(router)

	oauth := r.Group("/oauth")
	auth := SessionAuthHandler(builder, builder.Cache("user"), oauth.Router, "id", "Id")

	oauth.Security().OnFail(DefaultAuthFail)
	oauth.Security().Key("session", CookieLocation, SessionAuth, true)

	oauth.Get("/wechat", Swagger{
		Controllers: []Ctl{saveJump, user.Redirect},
		Params: []Param{
			{Name: "app", Default: client.App()},
			{Name: "channel", Default: "wechat_pc"},
			{Name: "jump", In: Query},
			{Name: "callback", Default: url + "/callback/wechat"},
		},
		Response: ApiResponse,
	})
	oauth.Get("/callback/wechat", Swagger{
		Controllers: []Ctl{user.Callback, auth.Login, jump},
		Params: []Param{
			{Name: "app", Default: client.App()},
			{Name: "channel", Default: "wechat_pc"},
			{Name: "code", In: Query},
			{Name: "state", In: Query},
			{Name: "open_id", In: Cache},
			{Name: "origin_id", In: Cache},
			{Name: "callback", Default: url + "/callback/wechat"},
		},
	})
	oauth.Get("/qq", Swagger{
		Controllers: []Ctl{saveJump, user.Redirect},
		Params: []Param{
			{Name: "app", Default: client.App()},
			{Name: "channel", Default: "qq_pc"},
			{Name: "jump", In: Query},
			{Name: "callback", Default: url + "/callback/qq"},
		},
		Response: ApiResponse,
	})
	oauth.Get("/callback/qq", Swagger{
		Controllers: []Ctl{user.Callback, auth.Login, jump},
		Params: []Param{
			{Name: "app", Default: client.App()},
			{Name: "channel", Default: "qq_pc"},
			{Name: "code", In: Query},
			{Name: "state", In: Query},
			{Name: "open_id", In: Cache},
			{Name: "origin_id", In: Cache},
			{Name: "callback", Default: url + "/callback/qq"},
		},
	})
}
